var dgram = require('dgram');
var udp_client = dgram.createSocket('udp4');
var readline = require('readline');
udp_client.bind(6666); // 绑定端口

/*
node-udp实现聊天功能
A 电脑开启 6666 端口, 发送到 8888 端口
B 电脑开启 8888 端口, 发送到 6666 端口
 */

var rl = readline.createInterface(process.stdin, process.stdout);
// rl.setPrompt('client > ');
rl.prompt();

rl.on('line', function(line) {
  var msg = line.trim();
  if(msg){
    msg = Buffer.from(msg)
    const len = msg.length
    udp_client.send(msg, 0, len, 8888, '127.0.0.1');
  }
  rl.prompt();
});

rl.on('close', function() {
  console.log('bye bye!');
  process.exit(0);
});

udp_client.on('close',function(){
  console.log('udp client closed.')
})

//错误处理
udp_client.on('error', function () {
  console.log('some error on udp client.')
})

// 接收消息
udp_client.on('message', function (msg,rinfo) {
  console.log(`receive message from ${rinfo.address}:${rinfo.port}：` + msg.toString());
  rl.prompt();
})

// 监听端口
// udp_client.on('listening', function () {
//   console.log('udp server linstening 5678.');
// })
// 关闭端口
// udp_client.close();
